package com.ken.ability.gateway.filter.limit;

import com.alibaba.fastjson.JSON;
import com.ken.entity.base.protocol.R;
import com.ken.entity.base.util.RCode;
import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 限流过滤器 - redis+lua脚本实现分布式限流
 */
@Data
public class TokenLimiterFilter implements GatewayFilter, Ordered {

    //令牌桶的存放map集合
    private Map<String, TokenTong> tokenMap = new HashMap<>();

    //最大令牌数
    private Integer maxTokens;
    //每秒生成令牌数
    private Integer secTokens;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //获得请求的url
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();

        //获取当前请求的令牌桶
        TokenTong tokenTong = tokenMap.computeIfAbsent(path,
                s -> new TokenTong(s, maxTokens, secTokens));

        //尝试获取令牌
        if(tokenTong.getTokenNow(1)) {
            //放行
            return chain.filter(exchange);
        }

        //无法获得令牌
        ServerHttpResponse response = exchange.getResponse();

        R result = new R()
                .setCode(RCode.TOO_FREQUENTLY.code)
                .setMessage(RCode.TOO_FREQUENTLY.message);

        DataBuffer dataBuffer = null;
        try {
            response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
            dataBuffer = response.bufferFactory()
                    .wrap(JSON.toJSONString(result).getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 200;
    }
}
